<?php
/**
 * XGPHP 轻量级PHP框架
 * @link http://xgphp.xg3.cn
 * @version 2.0.0
 * @license http://www.apache.org/licenses/LICENSE-2.0
 * @author 讯高科技 <xungaokeji@qq.com>
*/
namespace xg;
use \xg\facade\Config;
use \helper\Arr;
use xg\facade\Log;

class Cookie {
	protected $config = [
		'path' => '/',
		'secure'   => false,
		'httponly' => true,
		'samesite' => true,
	];
	protected $data=[];
	function __construct(){
		$config=Config::get('cookie');
		if(is_array($config)){
			$this->config($config);
		}
	}
	public function prefix($prefix=null){
		$this->config('prefix',$prefix);
		return $this;
	}
	public function config($config,$value=null){
		if(is_array($config)){
			$this->config=Arr::extend($this->config,$config);
		}elseif(is_string($config)){
			$this->config[$config]=$value;
		}
		return $this;
	}
	public function remove($name){
		$prefix=$this->config['prefix'];
		$this->data[$prefix.$name]=['value'=>null,'expire'=>-1];
	}
	public function clear($all_prefix=false){
		$prefix=$this->config['prefix'];
		foreach($this->data as $name=>$value){
			if($all_prefix or !$prefix or strpos($name,$prefix)===0){
				$this->data[$name]=['value'=>null,'expire'=>-1];
			}
		}
	}
	public function get($name){
		$prefix=$this->config['prefix'];
		$data = Arr::extend($_COOKIE,$this->data);
		if(isset($data[$prefix.$name])){
			if(substr($data[$prefix.$name],0,1)==='{' or substr($data[$prefix.$name],0,1)==='['){
				return json_decode($data[$prefix.$name],true);	
			}
			return $data[$prefix.$name];
		}
		if(isset($data[$name])){
			if(substr($data[$name],0,1)==='{' or substr($data[$name],0,1)==='['){
				return json_decode($data[$name],true);	
			}
			return $data[$name];
		}
	}
	public function set($name,$value,$data=[]) {
		$prefix=$this->config['prefix'];
		if($prefix and substr($name,0,strlen($prefix))!==$prefix){
			$name=$prefix.$name;
		}
		$this->data[$name]=Arr::extend($data,['value'=>$value]);
	}
	public function save(){
		foreach($this->data as $name=>$data) {
			$data=Arr::extend($this->config,$data);
			$expire=$data['expire']?($data['expire']+time()):0;
			$path=$data['path']?$data['path']:'/';
			$domain=$data['domain']?$data['domain']:null;

			if(is_array($data['value'])){
				$value=json_encode($data['value'],true);
			}else{
				$value=$data['value'];
			}
			if(PHP_VERSION_ID>=70300){
				setcookie($name,$value,[
					'expires'  => $expire,
					'path'     => $path,
					'domain'   => $domain,
					'secure'   => !!$data['secure'],
					'httponly' => !!$data['httponly'],
					'samesite' => !!$data['samesite'],
				]);
			}else{
				setcookie($name,$value,$expire,$path,$domain,$data['secure'],$data['httponly']);
			}
		}
	}
}
?>